<template>

      <div class="chart">
        <v-chart :option="option2"> </v-chart>
        <div class="inner">
          <div class="inner-title">累计订单量</div>
          <div class="inner-content">{{ total2 }}</div>
        </div>
      </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getcategorydataData } from '../api/index.js';

const option2 = ref({});

const categorydata = ref({});

const dataList2 = ref([]);
const data2 = ref([]);
const formdata = ref([]);

const renderChart = (data, option) => {
  option.value = {
    title: {
      text: '品类分布',
      textStyle: {
        color: '#797575',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}<br/>销售额: {c}',
    },
    legend: {
      orient: 'vertical',
      right: 10,
      align: 'left',
      formatter: function (name) {
        const target = data.find((item) => item.name === name);
        return target ? `${name}|${target.value}` : name;
      },
      textStyle: {
        color: '#797575',
        fontSize: 12,
      },
      show: true,
    },
    series: [
      {
        name: '品类分布',
        type: 'pie',
        radius: ['55%', '70%'],
        center: ['45%', '50%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        label: {
          show: true,
          position: 'outside', 
          formatter: '{b}', 
          color: '#333',
          fontSize: 12,
        },
        labelLine: {
          show: true, 
          length: 10, 
          length2: 20, 
        },
        data: data,
      },
    ],
  };
};

onMounted(async () => {
  categorydata.value = await getcategorydataData();
  commonfn(data2, option2, dataList2);
});

const total2 = computed(() => {
  return dataList2.value.reduce((acc, cur) => acc + cur, 0);
});


const commonfn = (datas, option, dataList) => {
  datas.value = categorydata.value.data2;
  dataList.value = datas.value.map((item) => item.value);
  formdata.value = datas.value.map((item) => {
    return {
      name: item.title,
      value: item.value, 
    };
  });
  renderChart(formdata.value, option);
};

</script>

<style scoped>

.chart {
  width: 100%;
  height: 470px;
  margin-top: 20px;
  position: relative;
}
.inner {
  position: absolute;
  top: 45%;
  left: 39%;
  text-align: center;
}
.inner-title {
  font-size: 14px;
  color: #797575;
}
.inner-content {
  font-size: 28px;
}
</style>
